package com.kingtone.rongji.ui;

import com.kingtone.rongji.R;
import com.kingtone.rongji.biz.Comments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 自定义弹出框
 * @author leilei.liu
 *
 */
public class CustomDialog {

	/**
	 * 为了确保整个应用同时只会弹出一个弹框，此处使用单例对象，每次显示下一个ALert之前调用dismiss关掉上一个弹框。
	 */
	private static Dialog mDialog;
	
	private CustomDialog() {
	}
	
	/**
	 * 关闭自定义弹框
	 */
	public static void dismiss() {
		if(null != mDialog && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}

	
	public static Dialog show(Activity activity, int level, String title, String advantage, String disvatange, String description, OnClickListener dismissAction) {
		// 逻辑异常的时候，可能在自定义Alert显示的情况下又去调用show方法，这里日志进行记录
		if(null != mDialog && mDialog.isShowing()) {
			Log.e("CustomDialog", "Auto close alert for show next alert.The pre alert:" + mDialog);
		}
		
		// 隐藏可能存在的上一个Alert
		dismiss();
		
		if (null == activity) {
			return null;
		}

		// 创建Alert对象
		final AlertDialog dlg = new AlertDialog.Builder(activity).create();
		dlg.show();
		
		Window window = dlg.getWindow();
		window.setContentView(R.layout.dialog_custom);

		// comments level
		TextView commentsLevel = (TextView) window.findViewById(R.id.my_comments_level);
		commentsLevel.setText(Comments.getLevelStr(level));
		Drawable drawable= activity.getResources().getDrawable(Comments.getLevelDrawable(level));  
		/// 这一步必须要做,否则不会显示.  
		drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());  
		commentsLevel.setCompoundDrawables(drawable,null,null,null); 
		//comments title
		TextView commentsTitle = (TextView) window.findViewById(R.id.my_comments_title);
		commentsTitle.setText(activity.getString(R.string.comments_title) + title);
		TextView commentsAdvanteage = (TextView) window.findViewById(R.id.my_comments_advantage);
		commentsAdvanteage.setText(activity.getString(R.string.comments_advantage) + advantage);
		TextView disVanteage = (TextView) window.findViewById(R.id.my_comments_disadvantage);
		disVanteage.setText(activity.getString(R.string.comments_disvantage) + disvatange);
		TextView commentsDetail = (TextView) window.findViewById(R.id.my_comments_detail);
		commentsDetail.setText(activity.getString(R.string.comments_description) + description);
		// 右上角取消按钮
		ImageView dismiss = (ImageView) window.findViewById(R.id.my_alert_dismiss);
			
		
		// 设置右上角点击按钮事件
		if(null != dismissAction) {
			dismiss.setOnClickListener(dismissAction);
		} else {
			dismiss.setVisibility(View.GONE);
		}
		
		mDialog = dlg;
		return dlg;
	}


}
